<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="出票时间" prop="outTime">
          <el-date-picker
              v-model="queryParams.outTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="!w-[240px]"
          />
        </el-form-item>
        <el-form-item label="旅行社名称" prop="deptId">
          <el-tree-select
              v-model="queryParams.deptId"
              placeholder="全部"
              :data="deptOptions"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryId">
          <el-tree-select
              v-model="queryParams.categoryId"
              placeholder="全部"
              :data="categoryOptions"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="车牌号码" prop="carNo">
          <el-input
              v-model="queryParams.carNo"
              placeholder="车牌号码"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="导游姓名" prop="guideName">
          <el-input
              v-model="queryParams.guideName"
              placeholder="导游姓名"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="出票人" prop="userName">
          <el-input
              v-model="queryParams.userName"
              placeholder="出票人"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search/>
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh/>
            </template>
            重置
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-switch v-model="showStats"></el-switch>
          <span style="margin-left: 10px;">显示统计</span>
        </el-form-item>
      </el-form>
    </div>
    <div class="search-bar" v-if="showStats">
      <div class="stats-container">
        <div v-show="noData">
          <span class="text-gray">暂无数据</span>
        </div>
        <div v-show="!noData" class="stat-item" v-for="stat in statsData" :key="stat.categoryName">
          <span class="label">{{ stat.categoryName }}</span>
          <span class="value">：{{ stat.num }}</span>
        </div>
      </div>
    </div>
    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['system:spotRecord:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus/>
          </template>
          新增
        </el-button>
        <el-button
            v-hasPerm="['system:spotRecord:delete']"
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon>
            <Delete/>
          </template>
          删除
        </el-button>
        <el-button v-hasPerm="['system:spotRecord:word']" type="primary" @click="handleExport()">
          <template #icon>
            <Download/>
          </template>
          导出
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column type="index" label="序号" width="80" align="center"/>
        <!--        <el-table-column-->
        <!--          key="createTime"-->
        <!--          label="出票时间"-->
        <!--          prop="createTime"-->
        <!--          min-width="200"-->
        <!--          align="center"-->
        <!--        />-->
        <el-table-column
            key="deptName"
            label="旅行社名称"
            prop="deptName"
            min-width="200"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="outTime"
            label="出票时间"
            prop="outTime"
            min-width="200"
            align="center"
        />
        <el-table-column
            key="userName"
            label="出票人"
            prop="userName"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="categoryName"
            label="分类名称"
            prop="categoryName"
            min-width="200"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column key="num" label="出票数量" prop="num" min-width="100" align="center"/>
        <el-table-column
            key="carNo"
            label="车牌号码"
            prop="carNo"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="guideName"
            label="导游姓名"
            prop="guideName"
            min-width="150"
            align="center"
        />

        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
                v-hasPerm="['system:spotRecord:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit/>
              </template>
              编辑
            </el-button>
            <el-button
                v-hasPerm="['system:spotRecord:delete']"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete/>
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 出票数据表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
        :close-on-click-modal="false"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="95px">
        <el-form-item label="旅行社名称" prop="deptId">
          <el-select
              v-model="formData.deptId"
              filterable
              remote
              reserve-keyword
              placeholder="请选择旅行社"
              :remote-method="remoteMethod"
              :loading="loadingQuery"
              style="width: 100%"
          >
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            >
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">{{ item.queryCode }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出票时间" prop="outTime">
          <el-date-picker
              v-model="formData.outTime"
              type="datetime"
              placeholder="出票时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
          />
        </el-form-item>

        <!--        <el-form-item label="出票日期" prop="outDate">-->
        <!--          <el-date-picker-->
        <!--            v-model="formData.outDate"-->
        <!--            type="datetime"-->
        <!--            placeholder="出票日期"-->
        <!--            value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--          />-->
        <!--        </el-form-item>-->

        <el-form-item label="分类名称" prop="categoryId">
          <el-tree-select
              v-model="formData.categoryId"
              placeholder="请选择分类名称"
              :data="categoryOptions"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="出票数量" prop="num">
          <el-input-number
              v-model="formData.num"
              placeholder="出票数量"
              :controls="false"
              :precision="0"
              maxlength="8"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="车牌号码" prop="carNo">
          <el-input v-model="formData.carNo" placeholder="车牌号码"/>
        </el-form-item>

        <el-form-item label="导游姓名" prop="guideName">
          <el-input v-model="formData.guideName" placeholder="导游姓名"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="loading" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import DeptAPI from "@/api/system/dept";
import SpotRecordAPI, {SpotRecordForm, SpotRecordPageQuery, SpotRecordPageVO,} from "@/api/system/spot-record";
import SpotCategoryAPI from "@/api/system/spot-category";

defineOptions({
  name: "SpotRecord",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);


interface ListItem {
  value: string
  label: string
  queryCode: string
}

const list = ref<ListItem[]>([])
const options = ref<ListItem[]>([])
const value = ref<string[]>([])
const loadingQuery = ref(false)

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);
const deptOptions = ref<OptionType[]>();
const deptQueryOptions = ref<OptionType[]>();
const categoryOptions = ref<OptionType[]>();
const now = new Date();
const startOfDay = new Date(now);
startOfDay.setHours(0, 0, 0, 0);

const endOfDay = new Date(now);
endOfDay.setHours(23, 59, 59, 999);

const format = (date: Date) => {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  const h = String(date.getHours()).padStart(2, '0');
  const mi = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${mi}:${s}`;
};

const queryParams = reactive<SpotRecordPageQuery>({
  pageNum: 1,
  pageSize: 10,
  outTime: [format(startOfDay), format(endOfDay)]
});

// 出票数据表格数据
const pageData = ref<SpotRecordPageVO[]>([]);
const showStats = ref(true); // 默认显示统计信息
const noData = ref(false); // 默认显示统计信息
// 统计数据
const statsData = ref<SpotRecordForm[]>([]);
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 出票数据表单数据
const formData = reactive<SpotRecordForm>({});

// 出票数据表单校验规则
const rules = reactive({
  deptId: [{required: true, message: "请选择旅行社", trigger: "blur"}],
  categoryId: [{required: true, message: "请选择分类名称", trigger: "blur"}],
  num: [
    {required: true, message: "请输入出票数量", trigger: "blur"},
    {
      validator: (rule: any, value: number, callback: any) => {
        if (value <= 0) {
          callback(new Error("出票数量必须大于0"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
});

/** 查询出票数据 */
function handleQuery() {
  loading.value = true;
  noData.value = false;
  SpotRecordAPI.getCount(queryParams)
      .then((data) => {
        if (data.length === 0) {
          noData.value = true;
        } else {
          const processedData = data.map(item => ({
            categoryName: item.categoryName || '未知分类',
            num: item.num || 0
          }));
          statsData.value = processedData;
        }
      })
      .catch(() => {
        // 异常情况下也显示“暂无数据”
        statsData.value = [{categoryName: '暂无数据', num: 0}];
      });

  SpotRecordAPI.getPage(queryParams)
      .then((data) => {
        pageData.value = data.list;
        total.value = data.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

/** 重置出票数据查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

const remoteMethod = (query: string) => {
  if (query) {
    loadingQuery.value = true
    setTimeout(() => {
      loadingQuery.value = false
      options.value = list.value.filter((item) => {
        const q = query.toLowerCase();
        return (
            item.queryCode?.toLowerCase().includes(q) ||
            item.label?.toLowerCase().includes(q)
        );
      })
    }, 200)
  } else {
    options.value = list.value
  }
}

/** 打开出票数据弹窗 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  // 加载区域下拉数据源
  deptOptions.value = await DeptAPI.getOptions();
  await loadDeptOptions()
  // 加载分类下拉数据源
  categoryOptions.value = await SpotCategoryAPI.getOptions();
  if (id) {
    dialog.title = "修改出票数据";
    SpotRecordAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增出票数据";
  }
}

/**
 * 加载所以旅行社信息
 */
async function loadDeptOptions() {
  try {
    const allDepts = await DeptAPI.getAllList(); // 获取全部部门数据
    list.value = allDepts.map((item) => {
      return {value: item.id, label: item.name, queryCode: item.queryCode}
    })
    options.value = list.value;
    console.log("获取或处理旅行社数据成功", options.value)
  } catch (error) {
    list.value = [];
    options.value = [];
    console.error("获取或处理旅行社数据失败", error);
  }
}

/** 提交出票数据表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SpotRecordAPI.update(id, formData)
            .then(() => {
              ElMessage.success("修改成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      } else {
        SpotRecordAPI.add(formData)
            .then((data) => {
              ElMessage({
                showClose: true,
                message: data,
                type: 'success',
                //duration: 3000, //显示时间，单位为毫秒。 设为 0 则不会自动关闭  默认3000
              })
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭出票数据弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除出票数据 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
      () => {
        loading.value = true;
        SpotRecordAPI.deleteByIds(ids)
            .then(() => {
              ElMessage.success("删除成功");
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      },
      () => {
        ElMessage.info("已取消删除");
      }
  );
}

function handleExport() {
  SpotRecordAPI.export(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
    const fileType =
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], {type: fileType});
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

if (onMounted) {
  onMounted(async () => {
    // 加载区域下拉数据源
    deptOptions.value = await DeptAPI.getOptions();
    // 加载分类下拉数据源
    categoryOptions.value = await SpotCategoryAPI.getOptions();
    handleQuery();
  });
}
</script>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}

:deep(.el-popper) {
  max-width: 300px;
}
</style>

<style scoped>
.stats-container {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.label {
  margin-right: 0px;
  font-size: 16px;
  color: #6331d3;
  font-weight: bold;
}

.value {
  font-size: 16px;
  color: #6331d3;
  font-weight: bold;
}
</style>

<style>
.text-gray {
  color: #999;
}
</style>
